package comeback.sort;

public class BubbleSort {
    public static void main(String[] args) {
        int[] num = new int[]{3,2,9,7,1,5,4};
        BubbleSort bubbleSort = new BubbleSort();
        bubbleSort.bubbleSort(num);
        for (int i : num) {
            System.out.println(i);
        }
    }

    public void bubbleSort(int[] num) {
        int n = num.length;
        for (int i = 0; i < num.length; i++) {
            boolean swapped = false;
            // TODO 每次定位一个最大的数字
            for (int j = 0; j < n - 1 - i; j++) {
                if (num[j] > num[j +1]) {
                    swap(num, j, j + 1);
                    swapped = true;
                }
            }
            // TODO 如果为发生交换表示本省就有序
            if (!swapped) {
                break;
            }
        }
    }

    private void swap(int[] num, int i, int j) {
        int tmp = num[i];
        num[i] = num[j];
        num[j] = tmp;
    }
}
